import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/check_in_rec_history_view_model.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/export_excel/export_excel_page.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/rule/check_in_rule_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'check_in_rec_num_widget.dart';
import 'choose_department_or_class/choose_filter_department_class_dialog.dart';

//02学员 04员工
const String TYPE_STAFF = '04';
const String TYPE_STU = '02';
const String TYPE_PARENT = '03';

///考勤 更多历史记录
class CheckInRecHistoryPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CheckInRecHistoryPage";

  ///当前月有考勤规则
  final bool hasRuleCurMonth;

  const CheckInRecHistoryPage({Key key, this.hasRuleCurMonth})
      : super(key: key);

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) async {
    String spPunchInCntKey =
        KEY_PUNCH_IN_RULE_CNT + UserRepository.getInstance().getCompanyId() ??
            '';
    int ruleCnt = await SharePreferenceUtil.getInt(spPunchInCntKey) ?? 0;
    return RouterUtils.routeForFutureResult(
      context,
      CheckInRecHistoryPage(
        hasRuleCurMonth: ruleCnt > 0,
      ),
      routeName: CheckInRecHistoryPage.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return CheckInRecHistoryPageState();
  }
}

class CheckInRecHistoryPageState extends BaseState<CheckInRecHistoryPage>
    with SingleTickerProviderStateMixin {
  CheckInRecHisViewModel viewModel;
  TabController _tabController;
  ValueNotifier<bool> _tabValueNotifier;

  List<String> _tabsList;
  List<Widget> _tabsViewList;

  static CheckInRecHistoryPageState of(BuildContext context) {
    ///获取state
    return context.findAncestorStateOfType<CheckInRecHistoryPageState>();
  }

  @override
  void initState() {
    super.initState();
    print('当月有考勤规则');
    if (UserRepository.getInstance().isCompany()) {
      _tabsList = ['员工'];
      _tabsViewList = [
        CheckInRecNumWidget(TYPE_STAFF, true),
      ];
    } else {
      _tabsList = ['员工', '学员', '家长'];
      _tabsViewList = [
        CheckInRecNumWidget(TYPE_STAFF, true),
        CheckInRecNumWidget(TYPE_STU, true),
        CheckInRecNumWidget(TYPE_PARENT, true)
      ];
    }
    viewModel = CheckInRecHisViewModel(this);
    _tabController = TabController(length: _tabsList?.length ?? 0, vsync: this);
    _tabValueNotifier = ValueNotifier(true);
    _tabController.addListener(() {
      //页面滑动时更新当前角色
      viewModel.roleType = _tabController.index == 2
          ? TYPE_PARENT
          : _tabController.index == 1 ? TYPE_STU : TYPE_STAFF;
      //重置筛选
      viewModel.chooseIdNotifier.value = null;
      //切换到家长时为false
      _tabValueNotifier.value = _tabController.index != 2;
      viewModel.refreshSubPage();
    });
    viewModel.monthDataNotifier.addListener(() {
      setState(() {
        // hasRule = viewModel.hasRule;
      });
    });
    refreshData();
  }

  void refreshData() {
    viewModel.queryHasPunchInRule();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Column(children: [
          _toTopBarWidget(),
          ValueListenableBuilder<bool>(
              valueListenable: viewModel.hasRuleNotifier,
              builder: (context, hasRule, child) {
                ///页面数据刷新时重置
                // resetRoleType();
                return Expanded(
                    child: Stack(
                  children: [
                    Container(
                      child: (hasRule ?? false)
                          ? getOrgContent()
                          : getNoRuleContent(),
                    ),
                    Align(
                      alignment: Alignment.bottomCenter,
                      child: GestureDetector(
                        onTap: () {
                          ExportExcelPage.navigatorPush(context);
                        },
                        child: Offstage(
                          offstage: false,
                          child: Container(
                              width: 160,
                              height: 40,
                              child: Center(
                                child: Text(
                                  '导出Excel',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.w600),
                                  textAlign: TextAlign.center,
                                ),
                              ),
                              decoration: BoxDecoration(
                                color: ThemeRepository.getInstance()
                                    .getPrimaryColor_1890FF(),
                                shape: BoxShape.rectangle,
                                borderRadius: BorderRadius.all(Radius.circular(24)),
                              ),
                              margin: EdgeInsets.only(bottom: 50)),
                        ),
                      ),
                    )
                  ],
                ));
              })
        ]),
      ),
      navigationBarColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///TopBar
  ///month 选择的月
  ///year   选择的日
  _toTopBarWidget() {
    return StreamBuilder<void>(
        stream: viewModel.dateStreamController.stream,
        builder: (context, snapshot) {
          return VgTopBarWidget(
            backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            isShowBack: true,
            centerWidget: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                //上个月
                _preMonthWidget(),
                //标题
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 6),
                  child: Center(
                    child: Text(
                      "${viewModel.year}年${viewModel.month}月",
                      style: TextStyle(color: Color(0xFFFFFFFF), fontSize: 17),
                    ),
                  ),
                ),
                //下个月
                _nextMonthWidget()
              ],
            ),
            rightWidget: _filter(),
            rightSecondWidget: _rule(),
            isShowSecondRightWdiget: false,
          );
        });
  }

  ///点击切换到上个月
  _preMonthWidget() {
    return GestureDetector(
      onTap: () {
        viewModel.chooseIdNotifier.value = null;
        resetRoleType();
        DateTime preMonth = DateTime(viewModel.year, viewModel.month - 1);
        viewModel.setDate(preMonth.year, preMonth.month);
        refreshData();
      },
      child: Padding(
        padding: const EdgeInsets.only(left: 20, top: 3),
        child: Image.asset(
          "images/calendar_previous_ico.png",
          height: 20,
        ),
      ),
    );
  }

  ///点击切换到下个月
  _nextMonthWidget() {
    bool isSameMonth = (DateTime.now().year == viewModel.year &&
        DateTime.now().month == viewModel.month);
    return GestureDetector(
      onTap: () {
        DateTime nextMonth = DateTime(viewModel.year, viewModel.month + 1);
        if (nextMonth.isAfter(DateTime.now())) {
          return;
        }
        resetRoleType();
        viewModel.chooseIdNotifier.value = null;
        viewModel.setDate(nextMonth.year, nextMonth.month);
        refreshData();
      },
      child: Padding(
        padding: const EdgeInsets.only(right: 20, top: 3),
        child: Opacity(
            opacity: isSameMonth ? 0.3 : 1,
            child: Image.asset(
              "images/calendar_next_ico.png",
              height: 20,
            )),
      ),
    );
  }

  ///筛选
  _filter() {
    return ValueListenableBuilder<bool>(
        valueListenable: viewModel.hasRuleNotifier,
        builder: (context, hasRule, child) {
          if (hasRule ?? false) {
            return SizedBox();
          }
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              EditTextAndValue bean = await ChooseFilterDepartmentClassPopWindow
                  .navigatorPushDialog(
                      context, viewModel.chooseIdNotifier.value?.value,
                      roleType: viewModel.roleType, roleChange: (roleType) {
                viewModel.roleType = roleType;
              });
              if (bean != null) {
                viewModel.chooseIdNotifier.value = bean;
                String chooseId = bean.value;
                if (StringUtils.isEmpty(chooseId)) {
                  resetRoleType();
                }
                viewModel.refreshSubPage();
              }
            },
            child: ValueListenableBuilder(
              valueListenable: viewModel.chooseIdNotifier,
              builder: (context, EditTextAndValue value, child) {
                return Container(
                  height: 45,
                  width: 30,
                  padding: EdgeInsets.only(top: 2, left: 10),
                  child: Stack(
                    children: [
                      Center(
                        child: Image.asset(
                          "images/shaixuan.png",
                          height: 20,
                          color: StringUtils.isNotEmpty(value?.value)
                              ? ThemeRepository.getInstance()
                                  .getPrimaryColor_1890FF()
                              : Colors.white,
                        ),
                      ),
                      Align(
                        alignment: Alignment.bottomCenter,
                        child: Image.asset(
                          "images/sanjiao.png",
                          height: 6,
                          width: 11,
                          color: StringUtils.isNotEmpty(value?.value)
                              ? Color(0xff1f3b63)
                              : Colors.transparent,
                        ),
                      )
                    ],
                  ),
                );
              },
            ),
          );
        });
  }

  ///筛选
  _filterTabBar() {
    return ValueListenableBuilder<bool>(
        valueListenable: _tabValueNotifier,
        builder: (context, isNotParent, child) {
          return Visibility(
            visible: isNotParent,
            child: ValueListenableBuilder<bool>(
                valueListenable: viewModel.hasRuleNotifier,
                builder: (context, hasRule, child) {
                  if (!(hasRule ?? false)) {
                    return SizedBox();
                  }
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () async {
                      EditTextAndValue bean =
                          await ChooseFilterDepartmentClassPopWindow
                              .navigatorPushDialog(context,
                                  viewModel.chooseIdNotifier.value?.value,
                                  offsetY: 45,
                                  hasRule: hasRule,
                                  roleChange: (val) {},
                                  roleType: _tabController?.index == 0
                                      ? TYPE_STAFF
                                      : _tabController?.index == 1
                                          ? TYPE_PARENT
                                          : TYPE_STU);
                      if (bean != null) {
                        viewModel.chooseIdNotifier.value = bean;
                        viewModel.roleType = _tabController?.index == 0
                            ? TYPE_STAFF
                            : _tabController?.index == 1
                                ? TYPE_PARENT
                                : TYPE_STU;
                        viewModel.refreshSubPage();
                      }
                    },
                    child: ValueListenableBuilder(
                      valueListenable: viewModel.chooseIdNotifier,
                      builder: (context, EditTextAndValue value, child) {
                        return Container(
                          height: 45,
                          width: 45,
                          padding: EdgeInsets.only(top: 2, left: 10, right: 15),
                          child: Stack(
                            children: [
                              Center(
                                child: Image.asset(
                                  "images/shaixuan.png",
                                  height: 20,
                                  color: StringUtils.isNotEmpty(value?.value)
                                      ? ThemeRepository.getInstance()
                                          .getPrimaryColor_1890FF()
                                      : Colors.white,
                                ),
                              ),
                              Align(
                                alignment: Alignment.bottomCenter,
                                child: Image.asset(
                                  "images/sanjiao.png",
                                  height: 6,
                                  width: 11,
                                  color: StringUtils.isNotEmpty(value?.value)
                                      ? Color(0xff1f3b63)
                                      : Colors.transparent,
                                ),
                              )
                            ],
                          ),
                        );
                      },
                    ),
                  );
                }),
          );
        });
  }

  ///规则
  _rule() {
    return GestureDetector(
      onTap: () {
        if (viewModel.hasRule == null) {
          return;
        }
        Future result = CheckInRulePage.navigatorPush(context, viewModel.rule);
        //返回后刷新,hasrule置为null，知道刷新结束后再更新
        result.then((value) {
          refreshData();
        });
      },
      child: Padding(
        padding: const EdgeInsets.only(left: 10, right: 15, top: 3),
        child: Image.asset(
          "images/rule.png",
          height: 20,
        ),
      ),
    );
  }

  ///有规则显示规则
  getOrgContent() {
    return Column(
      children: [
        _toTabBarWidget(),
        _chooseShowText(),
        Expanded(
          child: TabBarView(
            controller: _tabController,
            children: _tabsViewList,
          ),
        )
      ],
    );
  }

  Widget _toTabBarWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      height: 45,
      child: Row(
        children: [
          TabBar(
            controller: _tabController,
            isScrollable: true,
            indicatorSize: TabBarIndicatorSize.label,
            unselectedLabelStyle: TextStyle(
                color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                fontSize: 15),
            labelStyle: TextStyle(
              color:
                  ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
              fontSize: 15,
              fontWeight: FontWeight.w600,
            ),
            indicatorColor: (_tabsList?.length ?? 0) == 1
                ? Colors.transparent
                : ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
            indicatorPadding: EdgeInsets.only(left: 6, right: 6),
            tabs: List.generate(_tabsList?.length ?? 0, (index) {
              return Padding(
                padding: const EdgeInsets.only(bottom: 2.0),
                child: Text(_tabsList?.elementAt(index)),
              );
            }),
          ),
          Spacer(),
          _filterTabBar()
        ],
      ),
    );
  }

  ///无规则显示样式
  getNoRuleContent() {
    return Column(
      children: [
        _chooseShowText(),
        Expanded(
          child: (UserRepository.getInstance().isCompany())
              ?
              //企业默认显示员工
              CheckInRecNumWidget(TYPE_STAFF, false)
              //机构无默认
              : CheckInRecNumWidget(viewModel.roleType, false),
        )
      ],
    );
  }

  ///显示筛选的蓝条
  _chooseShowText() {
    return ValueListenableBuilder(
      valueListenable: viewModel.chooseIdNotifier,
      builder: (context, EditTextAndValue value, child) {
        if (value == null || value.value == null) {
          return SizedBox();
        }
        return Container(
          height: 30,
          width: double.infinity,
          alignment: Alignment.centerLeft,
          color: Color(0xff1f3b63),
          padding: EdgeInsets.only(left: 15),
          child: Text(
            value?.editText ?? '',
            style: TextStyle(
                fontSize: 12,
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF()),
          ),
        );
      },
    );
  }

  ///重置roleType
  void resetRoleType() {
    if (UserRepository.getInstance().isCompany()) {
      viewModel.roleType = TYPE_STAFF;
    } else {
      if (!viewModel.hasRule) {
        viewModel.roleType = null;
      } else {
        viewModel.roleType = _tabController.index == 2
            ? TYPE_STU
            : _tabController.index == 1 ? TYPE_PARENT : TYPE_STAFF;
      }
    }
  }
}
